package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"tb/cache"
	"tb/models/mysql"

	"tb/tbrpc/internal/svc"
	"tb/tbrpc/tbrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUpdateLogic {
	return &ProductUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductUpdateLogic) ProductUpdate(in *tbrpc.ProductUpdateRequest) (*tbrpc.ProductUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User

	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, fmt.Errorf("用户不存在")
	}
	var product mysql.Product
	if err := product.FindProductById(mysql.DB, in.ProductId); err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	product = mysql.Product{
		Model:  gorm.Model{ID: uint(in.ProductId)},
		Title:  in.Title,
		Price:  float64(in.Price),
		Number: int(in.Number),
		UserId: int(in.UserId),
	}
	err := product.ProductUpdate(mysql.DB)
	if err != nil {
		return nil, err
	}
	key := fmt.Sprintf("cart:*:%d", in.ProductId)
	result, _ := cache.Rdb.Keys(l.ctx, key).Result()
	for _, s := range result {
		m := map[string]interface{}{
			"title": in.Title,
			"price": in.Price,
		}
		cache.Rdb.HMSet(l.ctx, s, m)
	}
	return &tbrpc.ProductUpdateResponse{
		ProductId: int64(product.ID),
	}, nil
}
